This is a collection of code pieces that demonstrate the correct format and syntax of python code
String and integer are both common data types in Python
# This is a string
"Hello World"
# This is an integer
43
myvariable = "some text"
myvariable = input("Prompt text - what the user should write: ")
A user input or a string can be placed within the brackets
myvariable = int(## Whatever needs to be converted to an integer ##)
# myvariable starts off as "Hello World"
# This code is then run
myvariable.lower()
# myvariable is now "hello world"
print(f"This is a variable {var1} and another variable {var2}")
* / + -
if myvariable == "some value":
print("Response if true")
else:
print("Response if false")
if myvariable == "some value":
print("Response if true")
elif myvariable == "another value":
print("Response if also true")
# As many elifs as needed can go here
else:
print("Response if false")
These are used to test the relationship between two values
== != > < >= <=
Everything that happens inside of the loop must be indented from the left
myvariable = "the value of this variable"
while myvariable != "some value":
print("Incorrect - try again")
# Other lines of code can go here - such as asking the user to input a new value for the variable
#----- Anything below here is what happens when the while loop has ended
while True:
myvariable = input("Enter a value: ")
if myvariable == "some value":
print("Correct")
break
else:
print("Incorrect - try again!")
for i in range(0, 6):
print(i)
This outputs
0
1
2
3
4
5
mylist = ["thing 1", "thing 2", "thing 3", "thing 4", "thing 5"]
print(mylist[2])
print(mylist[4])
mylist = [
["apple", "fruit"],
["carrot", "vegetable"],
["grape", "fruit"],
["cabbage", "vegetable"],
["pear", "fruit"]
]
print(f"{mylist[2][0]} is a {mylist[2][1] )
print(f"{mylist[3][0]} is a {mylist[3][1] )
for i in range(0, 6):
print(listname[i])
for i in range(0, 6):
print(f"{listname[i][0]} is a character from {listname[i][1]}")